package io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NioServer1 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        System.out.println("服务已启动，监听8080端口");

        List<SocketChannel> channels = new ArrayList<>();
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while(true) {
            SocketChannel request = serverSocketChannel.accept();
            if(request != null) {
                request.configureBlocking(false); // 设置非阻塞模式
                System.out.println("建立连接：" + request.getRemoteAddress());
                channels.add(request);
            } else {
                Iterator<SocketChannel> iterator = channels.iterator();
                for (;iterator.hasNext();) {
                    SocketChannel channel = iterator.next();
                    buffer.clear();
                    if(channel.read(buffer) <= 0)
                        continue;
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    System.out.println("接收到的数据：" + new String(bytes));
                    System.out.println("数据来自：" + channel.getRemoteAddress());
                    channel.write(ByteBuffer.wrap("HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!\r\n".getBytes()));
                    System.out.println("发送响应完毕");

                    iterator.remove();
                }
            }
        }
    }
}
